/**
 * @author planderos
 */

//*** Ping the Stat Server *** ///
//statFeedNo = 1438;
//loadScript("http://myDivXConnected.com/pMaker/includes/statsPush.js");

loadScript("usernamePopup.js");
loadScript("parseMetadata.js");
loadScript("popup.js");
loadScript("infoPopup.js");
loadScript("pageParse.js");
//loadScript("movieParse.js");

var serviceXHR;
var feed = "http://www.netflix.com/NewWatchInstantlyRSS";
//var feed = "http://rss.netflix.com/QueueEDRSS?id=P1921924033361418529224065786175905";
//var feed = "http://www.netflix.com/TopWatchInstantlyRSS";
//var feed = "http://www.netflix.com/TopWatchInstantlyThisWeekRSS";
//var feed = "http://www.netflix.com/TopWatchInstantlyPastThreeMonthsRSS";

var main;
var mainDesc;
var title;
var path;
var desc;

var nowPlaying;
var playDate;
var playDesc;

var loginState = 0;

var	feedTitle = "New choices to watch instantly";

var movieId;
var trkid = 134852;

var cursorPosition = 1;

var netflixStorageUn = "NetflixUn";
var netflixUserId;
var netflixStoragePw = "NetflixPw";
var netflixPassword;

// XML Namespace resolver for XPath namespace resolution
function NSResolver(prefix) {
  var ns = {
    'cf': 'http://www.microsft.com/schemas/rss/core/2005'
  };
  return ns[prefix] || null;
}

// Takes a definition document and populates the various DCTK controls
function handleServiceResult(doc)
{
    // extract information with XPath
	
	main = doc.evaluate("//channel/title", doc, NSResolver, XPathResult.STRING_TYPE, null).stringValue;
	mainDesc = doc.evaluate("//channel/description", doc, NSResolver, XPathResult.STRING_TYPE, null).stringValue;
	
	results = doc.evaluate("count(//channel/item)", doc, NSResolver, XPathResult.ANY_TYPE, null).numberValue;
	
	title = new Array()
	for (var i = 1; i <= results; i++){
		title[i] = doc.evaluate("//channel/item[" + i + "]/title", doc, NSResolver, XPathResult.STRING_TYPE, null).stringValue;
		}
	path = new Array()
	for (var i = 1; i <= results; i++){
		path[i] = doc.evaluate("//channel/item["+ i +"]/guid", doc, NSResolver, XPathResult.STRING_TYPE, null).stringValue;
		}
	desc = new Array()
	for (var i = 1; i <= results; i++){
		desc[i] = doc.evaluate("//channel/item["+ i +"]/description", doc, NSResolver, XPathResult.STRING_TYPE, null).stringValue;
		}
    
    var dctk = connected.toolkit;

	createItemList();
}

function onServiceXHRStateChange()
{
    if (serviceXHR.readyState == 4) {
        if (serviceXHR.status == 200) {
            handleServiceResult(serviceXHR.responseXML);
        }
    }
}

function startServiceRequest()
{
	
	serviceXHR = new XMLHttpRequest();
	serviceXHR.open("GET", feed, true);
	serviceXHR.overrideMimeType('text/xml');
	serviceXHR.onreadystatechange = onServiceXHRStateChange;
	serviceXHR.send(null); 

}

function mainButtonHandler(e)
{
    switch(e.buttonId)
    {
        case dcKeyEvent.BUTTON_ID_BACK:
        {
            // navigate back
            if (window.history.length)
                window.history.back();
        }
        break;
		
		case dcKeyEvent.BUTTON_ID_MENU:
        {
            showPopup();
        }
        break;		

    }
}

function itemSelected()
{
	cursorPosition = itemList.curSel+1;
	movieId = desc[cursorPosition].split("small/")[1].split(".jpg")[0];
	connected.debug.print(movieId)
	metadataUrl = "http://www.netflix.com/JSON/BobData?linkCtr=BOX&movieid="+movieId;
	metaDesc = desc[cursorPosition];
	metaImg = "http://cdn-3.nflximg.com/us/boxshots/ghd/"+ desc[cursorPosition].split("small/")[1].split(".jpg")[0]+".jpg";
	
	//startMovieRequest(); //to get width/height
	showPlaybackPopup();

}

function createItemList(){
	var item;
	var dctk = connected.toolkit;
	for (var i = 1; i <= results && i <= 50; i++){
		item = itemList.addItem("id-0"+[i]);
    	item.text = title[i];
		item.img.src = "http://cdn-3.nflximg.com/us/boxshots/ghd/"+ desc[i].split("small/")[1].split(".jpg")[0]+".jpg";
	}
}

function onLoadComplete()
{
    var dctk = connected.toolkit;

    dctk.logicalWidth = 640;
    dctk.logicalHeight = 480;
    
    // create root panel
	var root = dctk.createPanelCtrl("root", true);
	root.width = 640;
	root.height = 480;
	root.backgroundStyle = dctkIElement.BACKGROUND_STYLE_IMAGE;
	root.backgroundImg.src = "background-01.png"
	root.color.rgb = 0xFFFFFF;
	root.onUnhandledKeyEvent = mainButtonHandler;
	dctk.rootPanel = root;
	
	var logo = dctk.createImageCtrl("logo", true);
	logo.img.src = "logo_netflix.png"
	logo.setRect(530, 390, 610, 440);
	root.addChild(logo);
	
	var mainTitle = dctk.createLabelCtrl("mainTitle", true);
    mainTitle.font = dctk.createFontByFacename("Arial Narrow", true, false);
    mainTitle.setRect(100, 395, 385, 435);
    mainTitle.textColor.rgb = 0xFFFFFF;
    mainTitle.fontSize = 24;
    mainTitle.align = dctkLabel.TS_CENTER;
	mainTitle.valign = dctkLabel.TS_MIDDLE;
    mainTitle.text = feedTitle;
    root.addChild(mainTitle);
	
	var header = dctk.createPanelCtrl("header", true);
	header.setRect(0, 450, 640, 480);
	header.backgroundStyle = dctkIElement.BACKGROUND_STYLE_IMAGE;
	header.backgroundImg.src = "chrome://connected/content/button_enabled.png"
	header.filled = true;
	header.color.rgb = 0x222222;
	root.addChild(header);
	
	itemList = dctk.createFilmstripCtrl("itemList", true);
    itemList.setRect(-150, 0, 635, 380);
	itemList.reflect = true;
	itemList.style = dctkIFilmstrip.FILMSTRIP_STYLE_HORIZONTAL_MIDDLE;
	itemList.scrollBarWidth = 0;
	itemList.textColor.rgb = 0xFFFFFF;
	itemList.onSelect = itemSelected;
	root.addChild(itemList);
	
	var connLogo = dctk.createImageCtrl("connLogo", true);
	connLogo.setRect(540, 5, 630, 75);
	connLogo.img.src = "chrome://connected/content/conn_logo.png";
	root.addChild(connLogo);
	
	var menuBtn = dctk.createButtonCtrl("menuBtn", true);
	menuBtn.setRect(560, 450, 640, 480);
	menuBtn.text = "Menu";
	menuBtn.fontSize = 22;
	menuBtn.onSelect = function(e) { showPopup(); }
	root.addChild(menuBtn);
	
	var queueBtn = dctk.createButtonCtrl("queueBtn", true);
	queueBtn.setRect(0, 450, 80, 480);
	queueBtn.text = "Queue";
	queueBtn.fontSize = 22;
	queueBtn.onSelect = function(e) { feedTitle = "My Queue"; startPageRequest(); }
	root.addChild(queueBtn);
	
	var newBtn = dctk.createButtonCtrl("newBtn", true);
	newBtn.setRect(80, 450, 160, 480);
	newBtn.text = "New";
	newBtn.fontSize = 22;
	newBtn.onSelect = function(e) { feedTitle = "New choices to watch instantly"; feed="http://www.netflix.com/NewWatchInstantlyRSS"; onLoadComplete(); }
	root.addChild(newBtn);
	
	var popBtn = dctk.createButtonCtrl("popBtn", true);
	popBtn.setRect(160, 450, 240, 480);
	popBtn.text = "Popular";
	popBtn.fontSize = 22;
	popBtn.onSelect = function(e) { feedTitle = "Last week's popular choices"; feed="http://www.netflix.com/TopWatchInstantlyThisWeekRSS"; onLoadComplete(); }
	root.addChild(popBtn);
	
	// set the sibling mappings
	menuBtn.leftSibling = popBtn;
	menuBtn.bottomSibling = itemList;
	menuBtn.rightSibling = queueBtn;
	queueBtn.bottomSibling = itemList;
	queueBtn.leftSibling = menuBtn;
	queueBtn.rightSibling = newBtn;
	newBtn.bottomSibling = itemList;
	newBtn.leftSibling = queueBtn;
	newBtn.rightSibling = popBtn;
	popBtn.bottomSibling = itemList;
	popBtn.leftSibling = newBtn;
	popBtn.rightSibling = menuBtn;
	itemList.topSibling = queueBtn;
	
	// start with the focus on the edit control
	dctk.focusedElement = itemList;
	
	// Input the email address you use for Netflix below
	var storageUn = connected.openStorage(netflixStorageUn,true);
	var username = storageUn.get(netflixUserId,username);
	//connected.debug.print(username);

// Input your password below
	var storagePw = connected.openStorage(netflixStoragePw,true);
	var password = storagePw.get(netflixPassword,password);
	//connected.debug.print(password);

	startServiceRequest();

	if (loginState == 0 && connected.clientID == "DCPC")
		{
			showPopup();
		}
		else if(connected.clientID != "DCPC")
		{
			showInfoPopup();
		}

	dctk.screenFade(1, 0, 0.5);
	
	//connected.toolkit.debug.drawElementOutline = true;
}

function redirectLogin()
{
	var params = connected.createPageDescriptor();
	params.uri = "login.htm";
	params.pageType = dcIConnected.PT_HTML;
	//params.viewConstraints.addResolutionConstraint(800,600);
	//params.viewConstraints.addAspectRatioConstraint(16, 9)
	//params.audioCapture = true;
	params.htmlInputFocusMode = dcIPageDescriptor.FOCUS_MODE_OBJECT;
	// load the page
	connected.debug.print("Playing: Login.htm");
	connected.loadFromPageDescriptor(params);
}

function redirectVideo()
{
	var params = connected.createPageDescriptor();
	params.uri = "http://www.netflix.com/WiPlayer?movieid="+movieId+"&trkid="+trkid;
	params.pageType = dcIConnected.PT_HTML;
	//params.viewConstraints.addResolutionConstraint(720,400);  //widescreen
	//params.viewConstraints.addResolutionConstraint(720,540);  //standard
	//params.viewConstraints.addResolutionConstraint(650,487);
	//params.audioCapture = true;
	params.htmlInputFocusMode = dcIPageDescriptor.FOCUS_MODE_OBJECT;
	// load the page
	connected.debug.print("Playing: http://www.netflix.com/WiPlayer?movieid="+movieId+"&trkid="+trkid);
	connected.loadFromPageDescriptor(params);
}

